<template>
	<view class="uni-data-pickerview">
		<!-- 全部新增，上面哪个搜索框 -->
		<div style="padding: 20rpx;display: flex;">
			<span style='height: 60rpx;line-height: 60rpx;'>搜索：</span> <input id='searchInput' v-model="searchValue"
				@input="handleInput" placeholder="  请输入"
				style="border: 1rpx solid grey; flex: 1;border-radius: 10rpx;height: 60rpx;line-height: 60rpx;padding: 0 20rpx;" />
		</div>
		<!-- 新增一个view 将之前的tab和下面的选项给包起来，方便我们隐藏 -->
		<view class="uni-data-pickerview" v-if="!searchContent">
			<scroll-view v-if="!isCloudDataList" class="selected-area" scroll-x="true">
				<view class="selected-list">
					<view class="selected-item" v-for="(item,index) in selected" :key="index" :class="{
              'selected-item-active':index == selectedIndex
            }" @click="handleSelect(index)">
						<text>{{item.text || ''}}</text>
					</view>
				</view>
			</scroll-view>
			<view class="tab-c">
				<scroll-view class="list" :scroll-y="true">
					<view class="item" :class="{'is-disabled': !!item.disable}"
						v-for="(item, j) in dataList[selectedIndex]" :key="j"
						@click="handleNodeClick(item, selectedIndex, j)">
						<text class="item-text">{{item[map.text]}}</text>
						<view class="check"
							v-if="selected.length > selectedIndex && item[map.value] == selected[selectedIndex].value">
						</view>
					</view>
				</scroll-view>

				<view class="loading-cover" v-if="loading">
					<uni-load-more class="load-more" :contentText="loadMore" status="loading"></uni-load-more>
				</view>
				<view class="error-message" v-if="errorMessage">
					<text class="error-text">{{errorMessage}}</text>
				</view>
			</view>

		</view>
		<!-- 全部新增，这个部分就是显示我们 -->
		<view class="uni-data-pickerview" style="overflow: auto;" v-else>
			<view>
				<view v-for="(item,index) of searchList" :key="index">
					<view style="padding: 40rpx 20rpx;margin:0 20rpx;border-bottom:1rpx solid grey"
						@click="handleNodeClick(item, 0, item.lastIndex)">
						<span>{{item.text}}</span>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import dataPicker from "./uni-data-picker.js"

	function debounce(fn, wait) {
		let timeout = null;

		return function() {
			let context = this;
			let args = arguments;

			// let callNow = !timeout;
			// 取消上一个timeout
			clearTimeout(timeout);
			timeout = null;
			timeout = setTimeout(() => {
				fn.apply(context, args)
				// if (timeout) clearTimeout(timeout);
			}, wait);
		};
	}
	/**
	 * DataPickerview
	 * @description uni-data-pickerview
	 * @tutorial https://ext.dcloud.net.cn/plugin?id=3796
	 * @property {Array} localdata 本地数据，参考
	 * @property {Boolean} step-searh = [true|false] 是否分布查询
	 * @value true 启用分布查询，仅查询当前选中节点
	 * @value false 关闭分布查询，一次查询出所有数据
	 * @property {String|DBFieldString} self-field 分布查询当前字段名称
	 * @property {String|DBFieldString} parent-field 分布查询父字段名称
	 * @property {String|DBCollectionString} collection 表名
	 * @property {String|DBFieldString} field 查询字段，多个字段用 `,` 分割
	 * @property {String} orderby 排序字段及正序倒叙设置
	 * @property {String|JQLString} where 查询条件
	 */
	export default {
		name: 'UniDataPickerView',
		emits: ['nodeclick', 'change', 'datachange', 'update:modelValue'],
		mixins: [dataPicker],
		props: {
			managedMode: {
				type: Boolean,
				default: false
			},
			ellipsis: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				// 搜索字段
				searchValue: '',
				searchContent: false, //显示搜索结果
				searchList: [] //搜索出来的列表（数组）
			}
		},
		created() {
			if (!this.managedMode) {
				this.$nextTick(() => {
					this.loadData();
				})
			}
		},
		methods: {
			onPropsChange() {
				this._treeData = [];
				this.selectedIndex = 0;
				this.$nextTick(() => {
					this.loadData();
				})
			},
			handleSelect(index) {
				this.selectedIndex = index;
			},
			handleNodeClick(item, i, j) {
				if (item.disable) {
					return;
				}

				const node = this.dataList[i][j];
				const text = node[this.map.text];
				const value = node[this.map.value];

				if (i < this.selected.length - 1) {
					this.selected.splice(i, this.selected.length - i)
					this.selected.push({
						text,
						value
					})
				} else if (i === this.selected.length - 1) {
					this.selected.splice(i, 1, {
						text,
						value
					})
				}

				if (node.isleaf) {
					this.onSelectedChange(node, node.isleaf)
					return
				}

				const {
					isleaf,
					hasNodes
				} = this._updateBindData()

				// 本地数据
				if (this.isLocalData) {
					this.onSelectedChange(node, (!hasNodes || isleaf))
				} else if (this.isCloudDataList) { // Cloud 数据 (单列)
					this.onSelectedChange(node, true)
				} else if (this.isCloudDataTree) { // Cloud 数据 (树形)
					if (isleaf) {
						this.onSelectedChange(node, node.isleaf)
					} else if (!hasNodes) { // 请求一次服务器以确定是否为叶子节点
						this.loadCloudDataNode((data) => {
							if (!data.length) {
								node.isleaf = true
							} else {
								this._treeData.push(...data)
								this._updateBindData(node)
							}
							this.onSelectedChange(node, node.isleaf)
						})
					}
				}
			},
			updateData(data) {
				this._treeData = data.treeData
				this.selected = data.selected
				if (!this._treeData.length) {
					this.loadData()
				} else {
					//this.selected = data.selected
					this._updateBindData()
				}
			},
			onDataChange() {
				this.$emit('datachange');
			},
			onSelectedChange(node, isleaf) {
				if (isleaf) {
					this._dispatchEvent()
				}

				if (node) {
					this.$emit('nodeclick', node)
				}
			},
			_dispatchEvent() {
				this.$emit('change', this.selected.slice(0))
			},
			// 搜索函数 ，再搜索框输入以后就会调用，然后生成要渲染的搜索结果列表，渲染到页面上 
			//   handleInput: debounce(function(e) {  如果看不懂这个，说明函数闭包的节流没学好，可以去补一下
			handleInput: debounce(function(e) {
				console.log('eeeeee', e.target.value)
				// 如果有值，就让搜索内容展示
				if (e.target.value) {
					// 打开搜索 关闭原生展示
					this.searchContent = true

					console.log('this.localdata', this.localdata)
					// 重置展示列表
					this.searchList = []

					// 这个是我们使用组件传递过来的本地数据，data里面是没有的，因为她放到uni-data-picker.js中了，这个无所谓，我们这里直接能调用到，只是给大家提个醒

					this.localdata.forEach((a,index) => {
						let sliceStart = a.text.indexOf(e.target.value)
						if (sliceStart > -1) {


							// 将他push到我的展示列表即可
							this.searchList.push({lastIndex:index,...a})
						}
					})
					console.log(this.searchList);
				} else {
					// 如果没有搜索词，那么就回到原始的展示
					this.searchContent = false
				}
			}, 1000),




			// 点击搜索选项后调用的函数
			chooseItem(e) {
				console.log('e.value', e.value)
				// 为什么这个结构？因为别人封装好了方法，就是需要这个结构
				let reinit = [e.frist, e.second, e.third]
				// 调用父级的更新函数，不需要懂，别人封装好的
				this.$emit('change', reinit)
				// 把搜索内容不显示
				this.searchContent = false
			},
		}
	}
</script>

<style lang="scss">
	$uni-primary: #007aff !default;

	.uni-data-pickerview {
		flex: 1;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		overflow: hidden;
		height: 100%;
	}

	.error-text {
		color: #DD524D;
	}

	.loading-cover {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(255, 255, 255, .5);
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		z-index: 1001;
	}

	.load-more {
		/* #ifndef APP-NVUE */
		margin: auto;
		/* #endif */
	}

	.error-message {
		background-color: #fff;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		padding: 15px;
		opacity: .9;
		z-index: 102;
	}

	/* #ifdef APP-NVUE */
	.selected-area {
		width: 750rpx;
	}

	/* #endif */

	.selected-list {
		/* #ifndef APP-NVUE */
		display: flex;
		flex-wrap: nowrap;
		/* #endif */
		flex-direction: row;
		padding: 0 5px;
		border-bottom: 1px solid #f8f8f8;
	}

	.selected-item {
		margin-left: 10px;
		margin-right: 10px;
		padding: 12px 0;
		text-align: center;
		/* #ifndef APP-NVUE */
		white-space: nowrap;
		/* #endif */
	}

	.selected-item-text-overflow {
		width: 168px;
		/* fix nvue */
		overflow: hidden;
		/* #ifndef APP-NVUE */
		width: 6em;
		white-space: nowrap;
		text-overflow: ellipsis;
		-o-text-overflow: ellipsis;
		/* #endif */
	}

	.selected-item-active {
		border-bottom: 2px solid $uni-primary;
	}

	.selected-item-text {
		color: $uni-primary;
	}

	.tab-c {
		position: relative;
		flex: 1;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		overflow: hidden;
	}

	.list {
		flex: 1;
	}

	.item {
		padding: 12px 15px;
		/* border-bottom: 1px solid #f0f0f0; */
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: space-between;
	}

	.is-disabled {
		opacity: .5;
	}

	.item-text {
		/* flex: 1; */
		color: #333333;
	}

	.item-text-overflow {
		width: 280px;
		/* fix nvue */
		overflow: hidden;
		/* #ifndef APP-NVUE */
		width: 20em;
		white-space: nowrap;
		text-overflow: ellipsis;
		-o-text-overflow: ellipsis;
		/* #endif */
	}

	.check {
		margin-right: 5px;
		border: 2px solid $uni-primary;
		border-left: 0;
		border-top: 0;
		height: 12px;
		width: 6px;
		transform-origin: center;
		/* #ifndef APP-NVUE */
		transition: all 0.3s;
		/* #endif */
		transform: rotate(45deg);
	}
</style>